<template>
  <section class="todoapp">
    <hm-header @add="fn1"></hm-header>
    <hm-main :list="showList" @del="fn" @changeset="handchange" @changeAll="changeAll"></hm-main>
    <hm-footer
      :list="list"
      :type="type"
      @remove="removeList"
      @changeType="typeOf"
      
    ></hm-footer>
  </section>
</template>

<script>
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todoList'))||[],
      type: "all",
    };
  },
  computed: {
    showList() {
      if (this.type === "all") {
        return this.list;
      } else if (this.type === "active") {
        return this.list.filter((item) => item.flag === false);
      } else {
        return this.list.filter((item) => item.flag === true);
      }
    },
  },
  methods: {
    changeAll(flag){
      this.list.forEach((item) => item.flag=flag)
    },
    fn(id) {
      // console.log(id);
      // 过滤,,不等于这个id的时候,留下来
      this.list = this.list.filter((item) => item.id != id);
    },
    fn1(value) {
      this.list.unshift({
        id: +new Date(),
        name: value,
        flag: false,
      });
    },
    handchange(flag, id) {
      // 根据id找到数组中中的对应项,进行更新find
      const obj = this.list.find((item) => item.id == id);
      // obj里的flag等于传过来的flag
      obj.flag = flag;
    },
    removeList() {
      this.list = this.list.filter((item) => item.flag === false);
    },
    typeOf(typel) {
      this.type = typel;
    },
  },
  watch:{
    list:{
      deep: true,
      handler(newValue) {
        localStorage.setItem('todoList',JSON.stringify(newValue))
      }
    }
  }
};
</script>

<style></style>
